<?php
class FrameworkModel extends model
{
	static $_instance = null;

	static function getInstance ()
	{
		if (is_null(self::$_instance)) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	
	function Permissions($id,$controller,$action)
	{
		// 取得用户信息
		$user =  $this->User($id);

		// 取得控制器信息
		$controller = $this->sql("select * from sys_controller where stop=0 and controller='[controller]' and action='[action]'",array('controller'=>$controller,'action'=>$action))->s(1);
		if($controller){
			
			// 判断用户类型
			switch ($user["ugroup"])
			{
				// 游客用户
				case 0:
					if($controller["guest"] == 1){
						return true;
					}
					break;
				// 顾客用户
				case 1:
					if($controller["customer"] == 1){
						return true;
					}
					break;
				// 管理员用户
				case 2:
					if($controller["administrator"] == 1){
						return true;
					}else{
						// 取得后台权限列表
						$perm = array();
						$per = $this->getUserPermissions($id);
						if($per != null)
						{
							$perm = explode(",",$per);
							if(in_array($controller["id"], $perm)){
								return true;
							}
						}
					}
					break;
			}
		}else{
			return true;
		}
		
		return false;
	}
	
	function User($id)
	{
		return $this->sql('select * from crm_user_view where id = [id]',array('id'=>$id))->s(1);
	}
	
	function getUser($username,$password){
		return $this->sql("select * from sys_user where stop=0 and ugroup = 2 and user='[user]' and password = md5('[password]')",array("user"=>$username,"password"=>$password))->s(1);
	}
	
	function getUserByName($username){
		return $this->sql("select * from sys_user where stop=0 and user='[user]'",array("user"=>$username))->s(1);
	}

    public function getUserById($id)
    {
        return $this->sql("select * from sys_user where stop=0 and id='[id]'",array("id"=>$id))->s(1);
    }
	function getUserPermissions($user){
		$str  = "SELECT permissions ";
		$str .= "from ( ";
        $str .= "      select su.id as user,GROUP_CONCAT(sr.permissions) as permissions ";
        $str .= "      from sys_user as su left join sys_user_role as sur on sur.stop=0 and su.id = sur.user ";
        $str .= "                          left join sys_role as sr on sr.stop=0 and sur.role = sr.id ";
        $str .= "      where su.stop = 0 ";
        $str .= "      group by su.id ";
        $str .= "     )permis ";
        $str .= "WHERE user=[user]";
        
        $return = $this->sql($str,array('user'=>$user))->s(1);
        
        return $return['permissions'];
	}
	
	function getMenusList($user)
	{
		$rs = array();
		$per = $this->getUserPermissions($user);
		if($per != null){

			$menu_list = $this->sql("SELECT *,CONCAT('/',controller,'/',action,'/') as path FROM sys_controller WHERE stop=0 and menu=1 and id in ($per) ORDER BY parent,orde,id")->s();
			foreach ($menu_list as $list){
				if ($list['parent']){
					$rs[$list['parent']][]=$this->getFill($list); 
				}else{
					$rs[0][]=$list;
				}
			}
		}

		return $rs;
	}
	
	function getFill($list){
		$list['name'] = str_pad($list['name'],40,'#');
		$list['name'] = str_replace('#', '&nbsp;', $list['name']);
		return $list;
	}
	
	function getAdminUser(){
		$sql  = "select su.*,ca.id as agency_id,ca.name as agency,cd.id as position_id,cd.name as position ";
		$sql .= "from sys_user as su left join crm_agency as ca on ca.stop=0 and su.agency_id=ca.id ";
        $sql .= "                    left join crm_position as cd on cd.stop=0 and su.position_id=cd.id ";
		$sql .= "where su.ugroup=2";
		return $this->sql($sql)->s();
	}
	
	function getRoleList(){
		return $this->sql("select * from sys_role order by id")->s();
	}
	
	function getRoleLink(){
		return $this->sql("select `user`,group_concat(role) as role from sys_user_role where stop=0 group by `user`")->s();
	}
	
	function getRoleBySid($p){
		return $this->sql("select role from sys_user_role where stop=0 and user=[sid] ",$p)->s();
	}
	
	function getMenusAllList()
	{
		return $this->sql("select * from sys_controller where menu=1 and stop=0 and (parent=0 or parent in (select id from sys_controller where menu=1 and stop=0)) order by parent,orde,id")->s();
	}
	
	function setRolePerm($prarm){
		if(trim($prarm['permissions'])==""){
			return $this->sql("update sys_role set `permissions` = null where id=[role]",$prarm)->u();
		}
		return $this->sql("update sys_role set `permissions` = '[permissions]' where id=[role]",$prarm)->u();
	}
	
	function setRole($prarm){
		return $this->sql("replace into sys_role (`name`)values('[name]')",$prarm)->i();
	}
	
	function delRole($prarm){
		return $this->sql("delete from sys_role where id = [id]",$prarm)->d();
	}
	
	function setUsersAdd($prarm){
		return $this->sql("insert into sys_user(`ugroup`,`user`,`password`,`agency_id`,`position_id`,`description`)values(2,'[user]','[password]','[agency]','[position]','[description]')",$prarm)->i();
	}
	
	function setUsersDel($prarm){
		return $this->sql("delete from sys_user where id=[id]",$prarm)->s();
	}
	
    function setUsersReplace($prarm){
		return $this->sql("update sys_user set stop = stop^1 where id=[id]",$prarm)->u();
	}
	
	function setUsersRepasswd($prarm){
		return $this->sql("update sys_user set password = '[password]' where id=[id]",$prarm)->u();
	}
	
	function setUsersEdit($prarm){
		return $this->sql("update sys_user set `agency_id`='[agency]',`position_id`='[position]',`description`='[description]' where id=[id]",$prarm)->u();
	}
	
	function setUserRole($prarm){
		$this->sql("delete from sys_user_role where `user`=[user]",array("user"=>$prarm["user"]))->d();
		foreach ($prarm["role"] as $val){
			$this->sql("insert into sys_user_role(`user`,`role`)values([user],[role])",array("user"=>$prarm["user"],"role"=>$val))->i();
		}
	}
}
?>